{% extends "base.html" %}

{% block content %}
<div class="container mt-4">
    <!-- 最新天气数据 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="card-title mb-0">最新天气数据</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover" id="currentWeatherTable">
                            <thead class="table-light">
                                <tr>
                                    <th>时间</th>
                                    <th>地点</th>
                                    <th>温度</th>
                                    <th>湿度</th>
                                    <th>天气</th>
                                    <th>风速/风向</th>
                                    <th>降水量</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td colspan="7" class="text-center">加载中...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 每日统计 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="card-title mb-0">每日天气统计</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover" id="dailyStatsTable">
                            <thead class="table-light">
                                <tr>
                                    <th>日期</th>
                                    <th>地点</th>
                                    <th>最高温度</th>
                                    <th>最低温度</th>
                                    <th>平均温度</th>
                                    <th>平均湿度</th>
                                    <th>总降水量</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td colspan="7" class="text-center">加载中...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 图表容器 -->
    <div class="chart-container">
        <div class="chart-box">
            <canvas id="dailyStatsChart"></canvas>
        </div>
    </div>
</div>

<script>
// 格式化日期时间
function formatDateTime(dateStr) {
    return new Date(dateStr).toLocaleString('zh-CN');
}

// 格式化数值
function formatNumber(num, decimals = 1) {
    return num !== null && num !== undefined ? Number(num).toFixed(decimals) : 'N/A';
}

// 加载最新天气数据
function loadCurrentWeather() {
    fetch('/api/weather/current')
        .then(response => response.json())
        .then(data => {
            console.log('获取到当前天气数据:', data);
            if (data.status === 'success') {
                const tbody = document.querySelector('#currentWeatherTable tbody');
                tbody.innerHTML = '';
                if (data.data && data.data.length > 0) {
                    data.data.forEach(item => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${formatDateTime(item.date_time)}</td>
                            <td>${item.location}</td>
                            <td>${formatNumber(item.temperature)}°C</td>
                            <td>${formatNumber(item.humidity)}%</td>
                            <td>${item.weather_condition || 'N/A'}</td>
                            <td>${formatNumber(item.wind_speed)} m/s ${item.wind_direction || ''}</td>
                            <td>${formatNumber(item.precipitation)} mm</td>
                        `;
                        tbody.appendChild(row);
                    });
                } else {
                    tbody.innerHTML = '<tr><td colspan="7" class="text-center">暂无数据</td></tr>';
                }
            } else {
                console.error('Error:', data.message);
                const tbody = document.querySelector('#currentWeatherTable tbody');
                tbody.innerHTML = `<tr><td colspan="7" class="text-center text-danger">加载失败: ${data.message}</td></tr>`;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            const tbody = document.querySelector('#currentWeatherTable tbody');
            tbody.innerHTML = '<tr><td colspan="7" class="text-center text-danger">加载失败</td></tr>';
        });
}

// 加载每日统计数据
function loadDailyStats() {
    fetch('/api/weather/stats/daily')
        .then(response => response.json())
        .then(data => {
            console.log('获取到每日统计数据:', data);
            if (data.status === 'success') {
                const tbody = document.querySelector('#dailyStatsTable tbody');
                tbody.innerHTML = '';
                if (data.data && data.data.length > 0) {
                    data.data.forEach(item => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${item.dt}</td>
                            <td>${item.location}</td>
                            <td>${formatNumber(item.max_temp)}°C</td>
                            <td>${formatNumber(item.min_temp)}°C</td>
                            <td>${formatNumber(item.avg_temp)}°C</td>
                            <td>${formatNumber(item.avg_humidity)}%</td>
                            <td>${formatNumber(item.total_precipitation)} mm</td>
                        `;
                        tbody.appendChild(row);
                    });
                    // 创建图表
                    createDailyStatsChart(data.data);
                } else {
                    tbody.innerHTML = '<tr><td colspan="7" class="text-center">暂无数据</td></tr>';
                }
            } else {
                console.error('Error:', data.message);
                const tbody = document.querySelector('#dailyStatsTable tbody');
                tbody.innerHTML = `<tr><td colspan="7" class="text-center text-danger">加载失败: ${data.message}</td></tr>`;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            const tbody = document.querySelector('#dailyStatsTable tbody');
            tbody.innerHTML = '<tr><td colspan="7" class="text-center text-danger">加载失败</td></tr>';
        });
}

// 创建每日统计图表
function createDailyStatsChart(data) {
    console.log("开始创建图表，数据:", data);

    const canvas = document.getElementById('dailyStatsChart');
    if (!canvas) {
        console.error('找不到图表容器元素');
        return;
    }

    const ctx = canvas.getContext('2d');
    if (!ctx) {
        console.error('无法获取canvas上下文');
        return;
    }

    try {
        // 准备数据
        const dates = data.map(item => item.dt);
        const maxTemps = data.map(item => item.max_temp);
        const minTemps = data.map(item => item.min_temp);
        const avgTemps = data.map(item => item.avg_temp);

        new Chart(ctx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [
                    {
                        label: '最高温度',
                        data: maxTemps,
                        borderColor: 'rgb(255, 99, 132)',
                        tension: 0.1
                    },
                    {
                        label: '平均温度',
                        data: avgTemps,
                        borderColor: 'rgb(54, 162, 235)',
                        tension: 0.1
                    },
                    {
                        label: '最低温度',
                        data: minTemps,
                        borderColor: 'rgb(75, 192, 192)',
                        tension: 0.1
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: '每日温度统计'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: false,
                        title: {
                            display: true,
                            text: '温度 (°C)'
                        }
                    }
                }
            }
        });
    } catch (error) {
        console.error('创建图表失败:', error);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log("页面加载完成，开始加载数据...");
    loadCurrentWeather();
    loadDailyStats();
});
</script>

<style>
.chart-container {
    width: 100%;
    max-width: 1200px;
    margin: 20px auto;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chart-box {
    position: relative;
    height: 400px;
    width: 100%;
}

.error-message {
    text-align: center;
    color: #dc3545;
    padding: 20px;
    font-size: 16px;
}

canvas {
    width: 100% !important;
    height: 100% !important;
}
</style>
{% endblock %}